import React, {PureComponent} from "react";
import {Icon, Popconfirm, Table} from "antd";
import {connect} from "react-redux";
import {paginationProps, tableProps} from "../../lib/ui";
import {del, getById, getTransportType, query, queryLinePrice, showModify} from "./actions";
import {query as coachQuery} from "../coach/actions";
import {getCurrentOrganization, getLastFilter, getPrincipal} from "../../lib/identity";
import {organizations} from "../home/actions";
import {query as lineQuery} from "../line/actions";
import {getVehicleFeesByCarrierId} from "../client/actions";
import {query as vehicleQuery} from "../vehicle/actions";
import {Resizable} from "react-resizable";

const LAST_FILTER = "carrier";

const ResizeableTitle = props => {
    const {onResize, width, ...restProps} = props;

    if (!width) {
        return <th {...restProps} />;
    }

    return (<Resizable
        width={width}
        height={0}
        onResize={onResize}
        draggableOpts={{enableUserSelectHack: false}}
    >
        <th {...restProps} />
    </Resizable>);
};

class List extends PureComponent {

    state = {
        columns: [{
            title: "供应商代码", dataIndex: "code", width: 150, render: (text, record) => (<a
                onClick={() => {
                    this.handleModify(record.id);
                }}
            >
                {text}
            </a>)
        }, {
            title: "供应商简称", dataIndex: "name", width: 150, ellipsis: true
        }, {
            title: "公司全称", dataIndex: "fullName", width: 200, ellipsis: true
        }, {
            title: "营业执照", dataIndex: "licence", width: 180
        }, {
            title: "结算周期(天)", dataIndex: "settlementDays", width: 100
        }, {
            title: "合同名称", dataIndex: "contractName", width: 180
        }, {
            title: "合同编号", dataIndex: "contractNumber", width: 180
        }, {
            title: "签订日期", dataIndex: "signedDate", width: 180
        }, {
            title: "结束日期", dataIndex: "expiresDate", width: 180
        }, {
            title: "到期提醒", dataIndex: "remindDate", width: 180
        }, {
            title: "所属抬头", dataIndex: "taiTou", width: 180
        }]
    };

    onPageChange = (page, pageSize) => {
        const {dispatch, filter} = this.props;
        dispatch(query({...filter, "currentOrgId": getCurrentOrganization(), page, pageSize}));
    };


    handleModify = id => {
        const {dispatch} = this.props;
        dispatch(getById(id));
        dispatch(getVehicleFeesByCarrierId({"ownerId": id}));
        dispatch(queryLinePrice({"belongId": id}));
        dispatch(showModify());
    };


    handleDeleteClient = id => {
        const {dispatch, filter} = this.props;
        dispatch(del(id)).then(() => {
            dispatch(query({...filter, "userId": getPrincipal().id, "currentOrgId": getCurrentOrganization()}));
        });
    };

    componentWillMount() {
        const {dispatch, page, pageSize} = this.props;
        let fields = getLastFilter(LAST_FILTER);
        if (fields === null || fields === undefined) {
            fields = {};
        }
        dispatch(query({
            "userId": getPrincipal().id, "currentOrgId": getCurrentOrganization(), ...fields, page, pageSize
        }));
        dispatch(getTransportType());
        dispatch(coachQuery());
        dispatch(lineQuery({}));
        dispatch(organizations(getPrincipal().id));
        dispatch(vehicleQuery({}));
    };

    handleResize = index => (e, {size}) => {
        this.setState(({columns}) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index], width: size.width,
            };
            return {columns: nextColumns};
        });
    };

    components = {
        header: {
            cell: ResizeableTitle,
        },
    };

    render() {
        const columns = this.state.columns;
        if (getPrincipal().admin) {
            const found = columns.find(item => item.title === '功能');
            if (!found) {
                columns.push({
                    title: '功能',
                    dataIndex: '',
                    key: 'x',
                    width: 50,
                    align: 'center',
                    fixed: 'right',
                    render: (text, record) => <span>
                    <Popconfirm title="确定删除此用供应商?" okText="是" cancelText="否"
                                onConfirm={() => this.handleDeleteClient(record.id)}>
                        <Icon type="delete"/>
                    </Popconfirm>
                </span>,
                });
            }
        }

        const resizeColumns = columns.map((col, index) => ({
            ...col, onHeaderCell: column => ({
                width: column.width, onResize: this.handleResize(index),
            }),
        }));

        const {
            page, pageSize, totalElements, dataSource, loading, filter
        } = this.props;
        const tablePagination = {
            ...paginationProps,
            total: totalElements,
            current: page,
            pageSize: pageSize,
            onShowSizeChange: (current, newSize) => this.onPageChange && this.onPageChange(1, newSize),
            onChange: this.onPageChange
        };

        return (<Table
            {...tableProps}
            columns={resizeColumns}
            components={this.components}
            scroll={{x: 1500}}
            pagination={tablePagination}
            dataSource={dataSource}
            loading={loading}
        />);
    }
}

const mapStateToProps = state => {
    return {
        ...state.carrier.list
    };
};

export default connect(mapStateToProps)(List);
